package com.opensource.common.jdk11config;

import org.slf4j.Logger;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;

//@Slf4j
public class jdk11_config {


    /**
     * 忽略非法反射警告  适用于jdk11
     */
    //public static void disableWarning() {
    //    try {
    //        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    //        theUnsafe.setAccessible(true);
    //        Unsafe u = (Unsafe) theUnsafe.get(null);
    //
    //        Class<?> cls = Class.forName("jdk.internal.module.IllegalAccessLogger");
    //        Field logger = cls.getDeclaredField("logger");
    //        u.putObjectVolatile(cls, u.staticFieldOffset(logger), null);
    //    } catch (Exception e) {
    //        // ignore
    //    }
    //}

    /**
     * 使用 VarHandles 来实现禁用非法反射警告
     */
    public static void disableWarning() {
        try {
            Class<?> cls = Class.forName("jdk.internal.module.IllegalAccessLogger");
            Field logger = cls.getDeclaredField("logger");
            VarHandle varHandle = MethodHandles.privateLookupIn(cls, MethodHandles.lookup())
                    .findVarHandle(cls, "logger", Logger.class);
            varHandle.setVolatile(null, null);
        } catch (Exception e) {
            // ignore
        }
    }
}
